package com.nitramf.catchmystream.entities.geo;

import java.util.LinkedList;
import java.util.List;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.spatial.geometry.LatLng;
import org.apache.lucene.spatial.tier.projections.CartesianTierPlotter;
import org.apache.lucene.spatial.tier.projections.IProjector;
import org.apache.lucene.spatial.tier.projections.SinusoidalProjector;
import org.apache.solr.util.NumberUtils;
import org.hibernate.search.bridge.FieldBridge;
import org.hibernate.search.bridge.LuceneOptions;

/**
 * Cartesian Tier Plotter to work with hibernate search
 * @see http://java.dzone.com/articles/spatial-search-hibernate
 */
public class CartesianTierFieldBridgeImpl implements FieldBridge {

    private static List<CartesianTierPlotter> ctps = new LinkedList<CartesianTierPlotter>();
    private static IProjector project = new SinusoidalProjector();

    static {
        setUpPlotter(2, 15);
    }

    private static void setUpPlotter(int base, int top) {

        for (; base <= top; base++) {
            ctps.add(new CartesianTierPlotter(base, project, CartesianTierPlotter.DEFALT_FIELD_PREFIX));
        }
    }

    @Override
    public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
        LatLng latLng = (LatLng) value;
        if (latLng == null) {
            return;
        }
        for (int i = 0; i < ctps.size(); i++) {
            CartesianTierPlotter ctp = ctps.get(i);
            document.add(new Field(ctp.getTierFieldName(),
                    NumberUtils.double2sortableStr(ctp.getTierBoxId(latLng.getLat(), latLng.getLng())), Field.Store.YES,
                    Field.Index.NOT_ANALYZED_NO_NORMS));
        }
    }
}
